package sf.core.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.PingppException;
import com.pingplusplus.model.Charge;

import sf.core.exception.SugarException;
import sf.core.service.PaymentService;

/**
 * Created by ligen on 16-3-8.
 */
public class PaymentServiceImpl implements PaymentService {

	private static final String apiKey = "sk_live_SjHremXojPDgGSAgFHoBdc0f";

	static {
		Pingpp.apiKey = apiKey;
	}

	private int unitPrice;
	private String appIdAndroid;
	private String appIdIos;

	public void setUnitPrice(int unitPrice) {
		this.unitPrice = unitPrice;
	}

	public void setAppIdAndroid(String appIdAndroid) {
		this.appIdAndroid = appIdAndroid;
	}

	public void setAppIdIOS(String appIdIos) {
		this.appIdIos = appIdIos;
	}

	@Override
	public int getUnitPrice() {
		return unitPrice;
	}

	@Override
	public String getAppId(int deviceType) throws SugarException {
		switch (deviceType) {
		case DEVICE_TYPE_ANDROID:
			return appIdAndroid;
		case DEVICE_TYPE_IOS:
			return appIdIos;
		default:
			throw new SugarException("Wrong device type");
		}
	}

	@Override
	public Charge charge(int amount, String channel, Long sn, String subject, int deviceType, String openId)
			throws SugarException {

		Map<String, Object> chargeMap = new HashMap<>();
		chargeMap.put("amount", amount);
		chargeMap.put("currency", "cny");
		chargeMap.put("subject", subject);
		chargeMap.put("body", "thank you");
		chargeMap.put("order_no", sn);
		chargeMap.put("channel", channel);
		chargeMap.put("client_ip", "127.0.0.1");
		Map<String, String> app = new HashMap<String, String>();
		app.put("id", getAppId(deviceType));
		chargeMap.put("app", app);
		if ("wx_pub".equals(channel)) {
			Map<String, String> extra = new HashMap<String, String>();
			extra.put("open_id", openId);
			chargeMap.put("extra", extra);
		}

		try {
			return Charge.create(chargeMap);
		} catch (PingppException e) {
			e.printStackTrace();
			throw new SugarException("创建订单失败");
		}

	}

}
